﻿/*
LICENCE___________________________________________________________________
    Copyright (C) 2012 Reverdy Sylvain

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
FIN LICENCE______________________________________________________________
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Controls;

namespace Merise_designer.Methodes
{

    /// <summary>
    /// Classe qui gère les fichiers de Backup pour les opérations "Annuler" et "Rétablir"
    /// </summary>
    public class Backup
    {
        private List<String> _backupFiles;
        private String _path;
        private String _folderName;
        private String _prefixFile;
        private int _idFile;
        private String _extFile;


        public Backup(String fileName)
        {
            _backupFiles = new List<string>();
            _folderName = "tmpBackup";
            _path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar +Configuration.appFolder +Path.DirectorySeparatorChar + _folderName + Path.DirectorySeparatorChar;
            if (!Directory.Exists(_path)) System.IO.Directory.CreateDirectory(_path);
            _prefixFile = fileName + "-bck-" + DateTime.Now.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds.ToString();
            _idFile = -1;
            _extFile = Configuration.extensionFile;
        }

        /// <summary>
        /// Enregistre un nouveau fichier de backup
        /// </summary>
        /// <returns>Retourne le nom du fichier (BDD) de sauvegarde en cours</returns>
        public String save()
        {
            _idFile++;
            String file = composeFullPathNameFile(_idFile);

            //Supprime le fichier de BDD si il existe   
            if (File.Exists(file))
            {
                File.Delete(file);
            }

            //Ajoute le nouveau fichier créé à la liste
            _backupFiles.Add(file);

            //TODO nettoyer la liste en supprimant les fichiers qui sont > idFile
            _backupFiles.RemoveRange(_idFile + 1, _backupFiles.Count - 1 - _idFile);
            //TODO : revoir lors de la création de asso/lignes

            return file;
        }

       /// <summary>
        /// Restaure le backup suivant "commande Rétablir"
       /// </summary>
       /// <returns>Le nom du fichier à restaurer</returns>
        public String restore()
        {
            if (!asNext())
            {
                return composeFullPathNameFile(_idFile);
            }
            else
            {
                _idFile++;
                return composeFullPathNameFile(_idFile);
            }
        }
        /// <summary>
        /// Restaure le backup précédent "commande Annuler"
        /// </summary>
        public String cancel()
        {
            if (!asBack())
            {
                return composeFullPathNameFile(_idFile);
            }
            else
            {
                _idFile--;
                return composeFullPathNameFile(_idFile);
            }
        }

        /// <summary>
        /// Traitement des archives backup lors de l'ouverture de l'application
        /// </summary>
        public void checkOnLoad()
        {
            if (Directory.GetFiles(_path).Count() > 0) removeAll();
        }
        
        /// <summary>
        /// Supprime toutes les archives
        /// </summary>
        public void removeAll()
        {
            foreach (String s in Directory.GetFiles(_path))
            {
                if (Path.GetFileName(s).Contains(_prefixFile)) File.Delete(s);
            }
        }

        public Boolean asNext()
        {
            return _idFile < _backupFiles.Count-1;
        }

        public Boolean asBack()
        {
            return (_idFile > 0);
        }
        ///// <summary>
        ///// Supprime les fichiers restants supérieurs au numéro actuel
        ///// </summary>
        //private void removeNexts()
        //{
        //    foreach (String s in Directory.GetFiles(_path))
        //    {
        //        if(Path.GetFileName()==composeFullPathNameFile(_idFile)) File.Delete(s);
        //    }
        //}

        /// <summary>
        /// Génère le nom absolu du fichier en cours
        /// </summary>
        /// <returns></returns>
        private String composeFullPathNameFile(int idFile)
        {
            return _path + _prefixFile + idFile + _extFile;
        }

    }
}
